package tbs.framework.utils.holders;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.NotImplementedException;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;

/**
 * 单例持有器，用于缓存单例对象。
 *
 * @author abstergo
 */

@Slf4j
public class SingletonHolder {
    /**
     * 使用volatile关键字保证可见性和有序性
     */
    private static volatile SingletonHolder instance = null;

    private final ConcurrentMap<Class<?>, Object> holderMap = new ConcurrentHashMap<>(16);

    public SingletonHolder() {
        if (instance == null) {
            synchronized (SingletonHolder.class) {
                if (instance == null) {
                    instance = this;
                }
            }
        }
    }

    /**
     * 获取指定类型的单例实例。
     *
     * @param clazz  类型
     * @param ifNull 无实例时的回调
     * @param <T>    泛型类型
     * @return 单例实例
     */
    public static <T> T getInstance(Class<? extends T> clazz, Function<Class<? extends T>, T> ifNull) {
        if (instance == null) {
            throw new NotImplementedException("please put instance into spring context");
        }
        return (T)instance.holderMap.computeIfAbsent(clazz, k -> ifNull.apply(clazz));
    }

    /**
     * 获取指定类型的单例实例。若不存在从spring容器中获取
     *
     * @param clazz 类型
     * @param <T>   泛型类型
     * @return 单例实例
     */
    public static <T> T getInstance(Class<? extends T> clazz) {
        return getInstance(clazz, HolderCommonFunction::fromSpringIfNullUseEmptyConstructor);
    }

}
